package cn.fl.fgi.util;

import cn.cmm.base.framework.constant.BaseConstant;
import cn.cmm.base.framework.exception.BaseException;
import cn.cmm.base.framework.logger.eum.LogExceptionEnum;
import cn.cmm.base.framework.logger.eum.LogOperEnum;
import cn.cmm.base.framework.utils.*;
import cn.cmm.cache.framework.utils.PropertiesCacheUtils;
import cn.fl.fgi.vo.FgiUpDetailVO;
import cn.fl.fgi.vo.FgiInportDataVO;
import cn.fl.framework.base.context.CurrentThreadContext;
import cn.fl.ref.fncprjbscinfo.util.DateUtil;
import cn.lb.framework.poi.excel.ExcelImportUtil;
import cn.lb.framework.poi.excel.entity.ImportParams;
import com.alibaba.fastjson.JSON;
import fl.constant.facade.framework.constant.BusinessIdConstant;
import fl.spl.facade.framework.constant.SplSystemConstant;
import fl.spl.facade.framework.enums.common.MagicNumReplaceEnum;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.net.URLConnection;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * Function: 经销商/挂靠公司评级导入
 * Created by Administrator on 2019-10-08 17:03:38.
 */
public class ImportFgiDataList {

    private static final Logger logger = LoggerFactory.getLogger(ImportFgiDataList.class);

    /**
     * 融担数据数据导入
     *
     * @param filePath 源文件路径
     * @return
     */
    public static Map<String, List<FgiUpDetailVO>> importFgiInportDataVOXls(String rootPath, String filePath, Map<String, String> starLvlCdNmMap, Long parseFileRecId) {
        String methodNm = "importSplRateRelInfoVOXls";
        boolean flag = true ;
        ImportParams params = new ImportParams();
        params.setTitleRows(BaseConstant.IS_YESNO_NO);//标题占用行数
        params.setHeadRows(BaseConstant.IS_YESNO_YES);//表头占用行数
        params.setNeedSave(false);//是否保存文件
        Map<String,String> tranTypMap = new HashMap<>();
        tranTypMap.put("1","本金");
        tranTypMap.put("2","利息");
        tranTypMap.put("3","代偿本金");
        tranTypMap.put("4","代偿利息");
        tranTypMap.put("5","追偿金额");
        tranTypMap.put("6","损失金额");

        Map<String,String> statusIdMap = new HashMap<>();
        statusIdMap.put("1","还款中-正常还款中");
        statusIdMap.put("2","合同结束-正常还款结束");
        statusIdMap.put("3","合同结束-提前还款");
        statusIdMap.put("4","还款中-逾期未代偿");
        statusIdMap.put("5","合同结束-逾期已代偿");
        statusIdMap.put("6","还款中-逾期部分代偿");

        Map<String, List<FgiUpDetailVO>> isSuccessSplRateRelInfosMap = null;
        Map<String, List<FgiUpDetailVO>> isFaildSplRateRelInfosMap = null;
        List<FgiInportDataVO> list = null;
        if (!filePath.contains("http")) {
            File file = new File(PropertiesCacheUtils.getProperty(rootPath) + filePath);
            if (file.exists()) {
                list = ExcelImportUtil.importExcel(file, FgiInportDataVO.class, params);
            }
        } else {
            InputStream in = null;
            URLConnection connection = null;
            try {
                URL url = new URL(filePath);
                connection = url.openConnection();//打开连接 获得URLConnection类的对象
                connection.setConnectTimeout(10000);
                connection.setReadTimeout(60000);
                in = connection.getInputStream();
                list = ExcelImportUtil.importExcel(in, FgiInportDataVO.class, params);
            } catch (IOException e) {
                BaseLogUtils.newServiceLogger("导入融担数据读取上传文件出错")
	    			.setLogOperType(LogOperEnum.REQ)
	    			.setSysCd(SplSystemConstant.SPL_SYS_CD)
	    			.setServiceCd(SplSystemConstant.LOG_SPL_SERVICE_CD)
	    			.setBussinessId(BusinessIdConstant.LOG_SPL_MANAGER_CD)
	    			.setThrowable(e)
	    			.setWarning(false)
	    			.warn(LogExceptionEnum.API_CODE_0102);
            } catch (Exception e) {
                BaseLogUtils.newServiceLogger("导入融担数据读取上传文件出错")
	    			.setLogOperType(LogOperEnum.REQ)
	    			.setSysCd(SplSystemConstant.SPL_SYS_CD)
	    			.setServiceCd(SplSystemConstant.LOG_SPL_SERVICE_CD)
	    			.setBussinessId(BusinessIdConstant.LOG_SPL_MANAGER_CD)
	    			.setThrowable(e)
	    			.setWarning(false)
	    			.error(LogExceptionEnum.API_CODE_0102);
            } finally {
                if (null != in) {
                    try {
                        in.close();
                    } catch (IOException e) {
                        BaseLogUtils.newServiceLogger("导入融担数据评级读取上传文件出错")
	    	    			.setLogOperType(LogOperEnum.REQ)
	    	    			.setSysCd(SplSystemConstant.SPL_SYS_CD)
	    	    			.setServiceCd(SplSystemConstant.LOG_SPL_SERVICE_CD)
	    	    			.setBussinessId(BusinessIdConstant.LOG_SPL_MANAGER_CD)
	    	    			.setThrowable(e)
	    	    			.setWarning(false)
	    	    			.error(LogExceptionEnum.API_CODE_0102);
                    }
                }
            }
        }
        //经销商/挂靠公司评分信息list
        List<FgiUpDetailVO> fgiUpDetailVOList = null;
        List<FgiUpDetailVO> faildUpDetailVOList = null;

        if (CollectionUtils.isNotEmpty(list)) {
            isSuccessSplRateRelInfosMap = new HashMap<>();
            isFaildSplRateRelInfosMap = new HashMap<>();
            fgiUpDetailVOList = new ArrayList<>(list.size());
            faildUpDetailVOList = new ArrayList<>(list.size());
            BaseLogUtils.newServiceLogger("导入融担数据")
				.setLogOperType(LogOperEnum.REQ)
				.setSysCd(SplSystemConstant.SPL_SYS_CD)
				.setServiceCd(SplSystemConstant.LOG_SPL_SERVICE_CD)
				.setBussinessId(BusinessIdConstant.LOG_SPL_MANAGER_CD)
				.setKeys("filePath",filePath,"记录数",""+list.size())
				.setWarning(false)
				.info();
            StringBuffer parseFailedCause = null;
            String errMsg = null;
            FgiUpDetailVO fgiUpDetailVO = null;
            Map<String, String> starNmAndLvlCdMap = null;
            if (CollectionUtils.isMapNotEmpty(starLvlCdNmMap)) {
                starNmAndLvlCdMap = new HashMap<>(starLvlCdNmMap.size());
                for (Map.Entry<String, String> entry : starLvlCdNmMap.entrySet()) {
                    starNmAndLvlCdMap.put(entry.getValue(), entry.getKey());
                }
            }
            boolean isSuccess = true;
            for (FgiInportDataVO vo : list) {
                try {
                    BaseLogUtils.newServiceLogger("导入融担数据")
                            .setLogOperType(LogOperEnum.REQ)
                            .setSysCd(SplSystemConstant.SPL_SYS_CD)
                            .setServiceCd(SplSystemConstant.LOG_SPL_SERVICE_CD)
                            .setBussinessId(BusinessIdConstant.LOG_SPL_MANAGER_CD)
                            .setKeys("filePath", filePath, "vo", JSON.toJSONString(vo))
                            .setWarning(false)
                            .info();
                    errMsg = null;
                    fgiUpDetailVO = new FgiUpDetailVO();
                    if (StringUtils.isNotEmpty(vo.getSequenceNo())) {
                        fgiUpDetailVO.setFundNo(vo.getSequenceNo().trim());
                    } else {
                        isSuccess = false;
                        errMsg = "导入数据序号为空！";
                        parseFailedCause = new StringBuffer();
                        parseFailedCause.append(errMsg);
                    }
                    if (StringUtils.isNotBlank(vo.getPayNo())) {
                        fgiUpDetailVO.setPayNo(vo.getPayNo().trim());
                    } else {
                        isSuccess = false;
                        errMsg = "导入数据支付表号为空！";
                        parseFailedCause = new StringBuffer();
                        parseFailedCause.append(errMsg);
                    }
                    if (StringUtils.isNotEmpty(vo.getCstNm())) {
                        fgiUpDetailVO.setCstNm(vo.getCstNm().trim());
                    } else {
                        isSuccess = false;
                        errMsg = "导入数据客户名称为空！";
                        parseFailedCause = new StringBuffer();
                        parseFailedCause.append(errMsg);
                    }
                    if (StringUtils.isNotEmpty(vo.getOrgNm())) {
                        fgiUpDetailVO.setPrjOrg(vo.getOrgNm().trim());
                    } else {
                        //isSuccess = false;
                        errMsg = "导入数据所属机构为空！";
                        parseFailedCause = new StringBuffer();
                        parseFailedCause.append(errMsg);
                    }
                    if (StringUtils.isNotEmpty(vo.getPrjTyp())) {
                        fgiUpDetailVO.setPrjType(vo.getPrjTyp().trim());
                    } else {
                        //isSuccess = false;
                        errMsg = "导入数据项目类型为空！";
                        parseFailedCause = new StringBuffer();
                        parseFailedCause.append(errMsg);
                    }
                    if (StringUtils.isNotEmpty(vo.getIsZGBus())) {
                        if ("是".equals(vo.getIsZGBus())) {
                            fgiUpDetailVO.setIsCap(BaseConstant.IS_YESNO_YES);
                        } else if ("否".equals(vo.getIsZGBus())) {
                            fgiUpDetailVO.setIsCap(BaseConstant.IS_YESNO_NO);
                        } else {
                            fgiUpDetailVO.setIsCap(Integer.valueOf(vo.getIsZGBus()));
                        }
                    } else {
                        isSuccess = false;
                        errMsg = "导入数据是否资管为空！";
                        parseFailedCause = new StringBuffer();
                        parseFailedCause.append(errMsg);
                    }
                    if (StringUtils.isNotEmpty(vo.getComNm())) {
                        fgiUpDetailVO.setOrgNm(vo.getComNm().trim());
                    } else {
                        isSuccess = false;
                        errMsg = "导入数据机构名称为空！";
                        parseFailedCause = new StringBuffer();
                        parseFailedCause.append(errMsg);
                    }
                    if (StringUtils.isNotEmpty(vo.getActPayTime())) {
                        if (DateUtils.formatStringToDate(vo.getActPayTime(), DateUtils.YYYY_MM_DD) == null) {
                            Calendar c = new GregorianCalendar(1900, 0, -1);
                            Date adate = org.apache.commons.lang3.time.DateUtils.addDays(c.getTime(), Integer.valueOf(vo.getActPayTime()));
                            fgiUpDetailVO.setOrgPayTm(DateUtils.formatDate(adate, DateUtils.YYYY_MM_DD));
                        } else {
                            fgiUpDetailVO.setOrgPayTm(DateUtils.formatStringToDate(vo.getActPayTime(), DateUtils.YYYY_MM_DD));
                        }
                    } else {
                        isSuccess = false;
                        errMsg = "导入数据机构实际付款时间为空！";
                        parseFailedCause = new StringBuffer();
                        parseFailedCause.append(errMsg);
                    }
                    if (StringUtils.isNotEmpty(vo.getDealType())) {
                        fgiUpDetailVO.setTranTypeId(vo.getDealType());
                        fgiUpDetailVO.setTranTypeNm(tranTypMap.get(vo.getDealType()));
                    } else {
                        //isSuccess = false ;
                        errMsg = "导入数据交易类型为空！";
                        parseFailedCause = new StringBuffer();
                        parseFailedCause.append(errMsg);
                    }
                    if (StringUtils.isNotEmpty(vo.getTscAmount())) {
                        fgiUpDetailVO.setTranTypeMoney(Double.valueOf(vo.getTscAmount()));
                    } else {
                        //isSuccess = false ;
                        errMsg = "导入数据交易类型对应金额为空！";
                        parseFailedCause = new StringBuffer();
                        parseFailedCause.append(errMsg);
                    }
                    if (StringUtils.isNotEmpty(vo.getReportStatus())) {
                        fgiUpDetailVO.setPayStatusId(Integer.valueOf(vo.getReportStatus()));
                        fgiUpDetailVO.setPayStatusNm(statusIdMap.get(vo.getReportStatus()));
                    } else {
                        //isSuccess = false;
                        errMsg = "导入数据上报支付表状态为空！";
                        parseFailedCause = new StringBuffer();
                        parseFailedCause.append(errMsg);
                    }
                    if (StringUtils.isNotEmpty(vo.getReportTime())) {
                        if (null == DateUtils.formatStringToDate(vo.getReportTime(), DateUtils.YYYY_MM_DD)) {
                            Calendar c = new GregorianCalendar(1900, 0, -1);
                            Date adate = org.apache.commons.lang3.time.DateUtils.addDays(c.getTime(), Integer.valueOf(vo.getReportTime()));
                            fgiUpDetailVO.setPayStatusTm(DateUtils.formatDate(adate, DateUtils.YYYY_MM_DD));
                        } else {
                            fgiUpDetailVO.setPayStatusTm(DateUtils.formatStringToDate(vo.getReportTime(), DateUtils.YYYY_MM_DD));
                        }
                    } else {
                        isSuccess = false;
                        errMsg = "导入数据上报支付表状态更新时间为空！";
                        parseFailedCause = new StringBuffer();
                        parseFailedCause.append(errMsg);
                    }
                    if (null != parseFailedCause && parseFailedCause.length() > BaseConstant.IS_YESNO_NO) {
                        //fgiUpDetailVO.setParseFailedCause(parseFailedCause.toString());
                        parseFailedCause.setLength(BaseConstant.IS_YESNO_NO);
                    }
                    fgiUpDetailVO.setPayStatus("1");
                    fgiUpDetailVO.setIsDel(BaseConstant.IS_YESNO_NO);
                    //fgiUpDetailVO.setOrgPayTm(new Date());
                    fgiUpDetailVO.setAnyStatus(BaseConstant.IS_YESNO_YES);

                    fgiUpDetailVO.setFgiUpDataId(parseFileRecId);
                    if (parseFailedCause != null) {
                        fgiUpDetailVO.setParseFailedCause(parseFailedCause.toString());
                    }
                    if (isSuccess) {
                        fgiUpDetailVOList.add(fgiUpDetailVO);
                    } else {
                        faildUpDetailVOList.add(fgiUpDetailVO);
                    }
                }catch(BaseException e){
                    isSuccess = false ;
                    errMsg = e.getMessage();
                    parseFailedCause = new StringBuffer();
                    parseFailedCause.append(errMsg);
                }
            }
                isSuccessSplRateRelInfosMap.put(BaseConstant.IS_YESNO_YES_STR, fgiUpDetailVOList);
                BaseLogUtils.newServiceLogger("导入融担数据,问题数据集合")
                    .setLogOperType(LogOperEnum.REQ)
                    .setSysCd(SplSystemConstant.SPL_SYS_CD)
                    .setServiceCd(SplSystemConstant.LOG_SPL_SERVICE_CD)
                    .setBussinessId(BusinessIdConstant.LOG_SPL_MANAGER_CD)
                    .setKeys("faildUpDetailVOList",JSON.toJSONString(faildUpDetailVOList))
                    .setWarning(false)
                    .info();
                //isSuccessSplRateRelInfosMap.put(BaseConstant.IS_YESNO_NO_STR, faildUpDetailVOList);

        } else {
            BaseLogUtils.newServiceLogger("导入融担数据")
				.setLogOperType(LogOperEnum.REQ)
				.setSysCd(SplSystemConstant.SPL_SYS_CD)
				.setServiceCd(SplSystemConstant.LOG_SPL_SERVICE_CD)
				.setBussinessId(BusinessIdConstant.LOG_SPL_MANAGER_CD)
				.setKeys("filePath",filePath,"记录数","0")
				.setWarning(false)
				.info();
        }
        return isSuccessSplRateRelInfosMap;
    }


    // 校验数字
    public static boolean checkFildIsNum(String field) throws BaseException {
        Pattern pattern = Pattern.compile("^(0|[1-9]+[0-9]*)(\\.[0]{1}\\d*|\\.[1-9]\\d*)?");
        Matcher isNum = pattern.matcher(field);
        if (!isNum.matches()) {
            return false;
        }
        return true;
    }
}
